<?php
/**
 * Created by PhpStorm.
 * User: kamlyli
 * Date: 2017/8/5
 * Time: 11:20
 */

namespace app\api\controller\v1;

use app\api\model\User;
use think\Request;


class Webapp extends Base
{
    // 获取cookie
    public function get_cookie(Request $request)
    {
        // 校验参数
        (new \app\api\validate\WebappValidate())->goCheck('get_cookie');

        // 获取 code rawData signature encryptedData  iv
        $param = $request->param();

        // 调用函数通过code获取openid
        $Wxapi_Agent = new \Wxapi();
        $webapp = $Wxapi_Agent->wx_get_webapp_openid($param['code']);
        if (!$webapp) {
            // TODO 记录日志 抛出异常
            return;
        }

        // 验证 signature = sha1(rawData+session_key)
        if ($param['signature'] != sha1($param['rawData'] . $webapp['session_key'])) {
            $param['session_key'] = $webapp['session_key'];
            // TODO 记录日志
        }

        // 通过 openid 检查是否需要新建用户
        $err_code = $Wxapi_Agent->aes128_cbc_decrypt($webapp['session_key'], $param['encryptedData'], $param['iv']);
        if (!$err_code) {
            $data['session_key'] = $webapp['session_key'];
            // TODO 记录日志 抛出异常
            return;
        }

        // 通过 openid 检查是否需要新建用户
        $weapp_user = json_decode($err_code, true);

        $user = new User();
        $user = $user->where('openId', $webapp['openid'])->find();

        if ($user) {
            if ($user->avatarUrl != $weapp_user['avatarUrl'] && $weapp_user['avatarUrl']) {
                $user->avatarUrl = $weapp_user['avatarUrl'];
                $user->save();
            }

            if ($user->nickName != $weapp_user['nickName'] && $weapp_user['nickName']) {
                $user->nickName = $weapp_user['nickName'];
                $user->save();
            }

        } else {
            $user = new User();
            $user->openId = $webapp['openid'];
            $user->nickName = $weapp_user['nickName'];
            $user->avatarUrl = $weapp_user['avatarUrl'];
            $user->save();
        }

        $data = [
            'id' => $user->id,
            'openId' => $webapp['openid'],
        ];

        // 返回 cookie
        $data = message_encrypt($data);
        return json_info($data);
    }
}